package com.bw.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import  com.bw.entity.User;
import com.bw.entity.UserRole;
import com.bw.mapper.RoleMapper;
import  com.bw.mapper.UserMapper;
import com.bw.mapper.UserRoleMapper;
import  com.bw.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 飓风微尘
 * @since 2022-05-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    public  Page<User>  listWithRole(int currentPage, int pageSize) {
        Page<User> page=new Page<User>(currentPage,pageSize);
        Page<User> pageList = userMapper.selectPage(page, null);
        List<User> records = pageList.getRecords();
        for (User record : records) {
           record.setRoleList(roleMapper.listRole(record.getUid()));
        }
        return pageList;
    }

    @Override
    public void add(User user) {
        boolean save = this.save(user);
        Integer[] rids = user.getRids();
        for (Integer rid : rids) {
            UserRole userRole = new UserRole();
            userRole.setUid(user.getUid());
            userRole.setRid(rid);
            userRoleMapper.insert(userRole);
        }
    }

    @Override
    @Transactional
    public void updateWithRole(User user) {
        this.updateById(user);
        userRoleMapper.removeByUid(user.getUid());
        Integer[] rids = user.getRids();
        for (Integer rid : rids) {
            UserRole userRole = new UserRole();
            userRole.setUid(user.getUid());
            userRole.setRid(rid);
            userRoleMapper.insert(userRole);
        }
    }

    @Override
    @Transactional
    public void del(Integer uid) {
        User user = new User();
        user.setUid(uid);
        userMapper.deleteById(user);
        userRoleMapper.removeByUid(uid);
    }


}
